package cn.derry.util;

import java.io.*;

/**
 * @author MangoDai
 * @decription 序列化
 * @date 2017/12/20
 **/
public class SerializerUtil {
    /**
     * 对象序列化
     *
     * @param obj
     * @return
     */
    public static byte[] serialize(Object obj) {
        ByteArrayOutputStream bai = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(bai);
            oos.writeObject(obj);
            oos.flush();
            bai.flush();
            byte[] byt = bai.toByteArray();
            return byt;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
                bai.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 对象反序列化
     *
     * @param byt
     * @return
     */
    public static Object unserizlize(byte[] byt) {
        ObjectInputStream oii = null;
        ByteArrayInputStream bis = new ByteArrayInputStream(byt);
        try {
            oii = new ObjectInputStream(bis);
            Object obj = oii.readObject();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                oii.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
